package com.maxd.adapter;


import com.maxd.error.ExceptionEnum;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.AdminInfo;
import com.maxd.model.Token;
import com.maxd.model.UserInfo;
import com.maxd.service.token.ITokenService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    private final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);
    @Autowired
    private ITokenService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        response.setHeader("Access-Control-Allow-Origin", "*");
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String requestPath = request.getRequestURI();
        log.debug("Method: " + method.getName() + ", IgnoreSecurity: " + method.isAnnotationPresent(IgnoreSecurity.class));
        log.debug("requestPath: " + requestPath);
        if (requestPath.contains("/swagger") || requestPath.contains("/configuration/ui")) {
            return true;
        }
        if (requestPath.contains("/douyin") || requestPath.contains("/wph") || requestPath.contains("/jd") || requestPath.contains("/pdd") || requestPath.contains("/error") || requestPath.contains("/taobao") || requestPath.contains("/wx")) {
            return true;
        }
        if (method.isAnnotationPresent(IgnoreSecurity.class)) {
            return true;
        }
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            Result error = ResultUtil.error(ExceptionEnum.WRONT_TOKEN);
            log.debug("token: " + error);
            throw new Exception("用户信息失效,请重新登录");
        }

        Token userId = userService.getUserByUuid(token);
        if (userId != null && userId.getUserId()!=null) {
            UserInfo userById = userService.getUserById(Long.parseLong(userId.getUserId()));
            if(userById==null){
                request.setAttribute("userId", null);
                Result error = ResultUtil.error(ExceptionEnum.WRONT_TOKEN);
                log.debug("token: " + error);
                throw new Exception("用户信息失效,请重新登录");
            }else if(!userById.getState().equals("true")){
                request.setAttribute("userId", null);
                Result error = ResultUtil.error(ExceptionEnum.LIMIT_USER);
                log.debug("token: " + error);
                throw new Exception("账户已被禁用，请联系客服处理！");
            }
            request.setAttribute("userId", userId.getUserId());
        } else if(userId != null && userId.getAdminId()!=null){
            AdminInfo adminById = userService.getAdminId(Long.parseLong(userId.getAdminId()));
            if(adminById==null){
                request.setAttribute("userId", null);
                Result error = ResultUtil.error(ExceptionEnum.WRONT_TOKEN);
                log.debug("token: " + error);
                throw new Exception("用户信息失效,请重新登录");
            }
            request.setAttribute("adminId", userId.getAdminId());
        } else{
            request.setAttribute("userId", null);
            Result error = ResultUtil.error(ExceptionEnum.WRONT_TOKEN);
            log.debug("token: " + error);
            throw new Exception("用户信息失效,请重新登录");
        }



        return true;
    }
}
